package com.heima.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.heima.utils.thread.AdminThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/29
 */
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录
     * @param dto
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        if (ObjectUtil.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (ObjectUtil.isEmpty(adUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String pwd = MD5Utils.encodeWithSalt(password, salt);
        if (!pwd.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Integer id = adUser.getId();
        AdUser user = new AdUser();
        user.setId(id);
        AdminThreadLocalUtil.setUser(user);

        String token = AppJwtUtil.getToken(Long.valueOf(id.toString()));
        Map<String, Object> map = new HashMap<>();
        map.put("user", adUser);
        map.put("token", token);
        log.info("用户登录，id：{}", id);
        return ResponseResult.okResult(map);
    }
}
